package sharetime.util;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class XmlUtil {

	public static String getContainedText(Node parent, String childTagName) {
		try {
			Node tag = ((Element) parent).getElementsByTagName(childTagName)
					.item(0);
			return ((Text) tag.getFirstChild()).getData();
		} catch (Exception e) {
			return null;
		}
	}

	public static Element getSingleChildElement(Element el, String name) {
		NodeList children = el.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);
			if (node.getNodeType() == 1 && name.equals(node.getNodeName()))
				return (Element) node;
		}

		return null;
	}

	public static String getAttributeWithDefault(Element element,
			String attributeName, String defaultValue) {
		String group = element.getAttribute(attributeName);
		if (group == null || "".equals(group.trim()))
			group = defaultValue;
		return group;
	}

	public static String escape(String source) {
		if (source == null)
			return "";
		StringBuffer pBuffer = new StringBuffer(source.length() + 30);
		for (int i = 0; i < source.length(); i++)
			escape(pBuffer, source.charAt(i));

		return pBuffer.toString();
	}

	public static String escapeForCdata(String source) {
		if (source == null)
			return null;
		StringBuffer sb = new StringBuffer();
		int oldIndex = 0;
		int index;
		while ((index = source.indexOf("]]>", oldIndex)) > -1) {
			sb.append(source.substring(oldIndex, index));
			oldIndex = index + 3;
			sb.append("]]]]><![CDATA[>");
		}
		sb.append(source.substring(oldIndex));
		return sb.toString();
	}

	private static String getEntityRef(char ch) {
		switch (ch) {
		case 60: // '<'
			return "lt";

		case 62: // '>'
			return "gt";

		case 34: // '"'
			return "quot";

		case 39: // '\''
			return "apos";

		case 38: // '&'
			return "amp";
		}
		return null;
	}

	public static String escape(char ch) {
		StringBuffer sb = new StringBuffer();
		escape(sb, ch);
		return sb.toString();
	}

	private static void escape(StringBuffer sb, char ch) {
		String charRef = getEntityRef(ch);
		if (charRef != null)
			sb.append("&").append(charRef).append(";");
		else if (ch >= ' ' && ch <= _lastPrintable && ch != '\367'
				|| ch == '\n' || ch == '\r' || ch == '\t')
			sb.append(ch);
		else
			sb.append("&#").append(Integer.toString(ch)).append(";");
	}

	private static int _lastPrintable = 126;

}
